<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>我的购物车 - 绿蜂巢农产品</title>
    <!-- 引入公共CSS -->
    <link rel="stylesheet" href="static/css/styles.css">
    <!-- 购物车专属样式 -->
    <style>
        .cart-page {
            padding: 20px;
            max-width: 1000px;
            margin: 0 auto;
        }

        .cart-container {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 20px;
        }

        .cart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .cart-title {
            font-size: 24px;
            color: #333;
        }

        .checkout-btn {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
        }

        .checkout-btn:hover {
            background-color: #218838;
        }

        .empty-cart {
            text-align: center;
            padding: 50px 0;
        }

        .empty-cart a {
            color: #007bff;
            text-decoration: none;
        }

        .empty-cart a:hover {
            text-decoration: underline;
        }

        .cart-list {
            margin-bottom: 20px;
        }

        .cart-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }

        .cart-item-image {
            width: 80px;
            height: 80px;
            margin-right: 15px;
        }

        .cart-item-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 4px;
        }

        .cart-item-name {
            flex: 1;
            font-weight: bold;
        }

        .cart-item-price {
            width: 100px;
            text-align: center;
        }

        .quantity-control {
            display: flex;
            align-items: center;
            width: 80px;
            justify-content: center;
        }

        .quantity-input {
            width: 100%;
            height: 30px;
            text-align: center;
            border: 1px solid #ddd;
        }

        .delete-btn {
            width: 30px;
            height: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #dc3545;
            cursor: pointer;
        }

        .cart-summary {
            text-align: right;
            padding: 15px 0;
            border-top: 1px solid #ddd;
        }

        .summary-title {
            margin-bottom: 15px;
            font-size: 18px;
            font-weight: bold;
        }

        .total-price {
            color: #dc3545;
            font-size: 20px;
        }

        .item-subtotal {
            width: 120px;
            text-align: right;
            font-weight: bold;
            color: #dc3545;
        }

        /* 支付模态框样式 */
        .payment-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }

        .payment-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border: 1px solid #888;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
            animation: modalFadeIn 0.3s;
        }

        @keyframes modalFadeIn {
            from {opacity: 0; transform: translateY(-20px);}
            to {opacity: 1; transform: translateY(0);}
        }

        .payment-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .close-btn {
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .payment-product-info {
            margin-bottom: 20px;
        }

        .product-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #eee;
        }

        .product-image {
            width: 60px;
            height: 60px;
            margin-right: 15px;
        }

        .product-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 4px;
        }

        .product-details {
            flex: 1;
        }

        .product-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .product-quantity {
            font-size: 14px;
            color: #666;
        }

        .product-price {
            font-weight: bold;
            color: #e63946;
            margin-left: 10px;
        }

        .payment-total {
            margin: 15px 0;
            padding: 10px;
            border-top: 1px solid #eee;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            font-weight: bold;
        }

        .payment-form {
            margin-top: 20px;
        }

        .payment-method {
            display: flex;
            align-items: center;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .payment-method.selected {
            border-color: #28a745;
            background-color: #f0fdf4;
        }

        .payment-method input {
            margin-right: 10px;
        }

        .payment-button {
            width: 100%;
            background-color: #28a745;
            color: white;
            border: none;
            padding: 12px;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .payment-button:hover {
            background-color: #218838;
        }

        .success-message {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #10b981;
            color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
            z-index: 1001;
            animation: successFadeIn 0.3s;
        }

        @keyframes successFadeIn {
            from {opacity: 0; transform: translate(-50%, -50%) scale(0.8);}
            to {opacity: 1; transform: translate(-50%, -50%) scale(1);}
        }
    </style>
</head>
<body>
<!-- 引入头部（包含登录状态判断的购物车图标） -->
<jsp:include page="header.jsp" />

<main class="cart-page">
    <div class="cart-container">
        <div class="cart-header">
            <h2 class="cart-title">我的购物车</h2>
            <c:if test="${not empty sessionScope.cart}">
                <!-- 修改：传递用户登录状态 -->
                <button class="checkout-btn" onclick="checkout(${not empty sessionScope.user})">去结算</button>
            </c:if>
        </div>

        <c:if test="${empty sessionScope.cart}">
            <div class="empty-cart">
                <p>购物车为空，<a href="products">去首页逛逛</a></p>
            </div>
        </c:if>

        <c:if test="${not empty sessionScope.cart}">
            <div class="cart-list">
                <!-- 购物车商品循环 -->
                <c:forEach items="${sessionScope.cart}" var="entry" varStatus="status">
                    <div class="cart-item" data-id="${entry.key}" data-price="<fmt:formatNumber value='${entry.value.price}' pattern='#0.00'/>">
                        <div class="cart-item-image">
                            <!-- 修正图片路径，处理可能为空的情况 -->
                            <c:choose>
                                <c:when test="${not empty entry.value.product.photo}">
                                    <img src="static/photo/${entry.value.product.photo}" alt="${entry.value.productName}">
                                </c:when>
                                <c:otherwise>
                                    <img src="static/photo/default.jpg" alt="${entry.value.productName}">
                                </c:otherwise>
                            </c:choose>
                        </div>
                        <div class="cart-item-name">${entry.value.productName}</div>
                        <div class="cart-item-price">
                            <fmt:formatNumber value="${entry.value.price}" pattern="#0.00"/>元
                        </div>
                        <div class="quantity-control">
                            <!-- 修复：确保productId正确传递 -->
                            <input type="number" class="quantity-input" value="${entry.value.quantity}" min="1" max="99"
                                   data-product-id="${entry.key}" onchange="updateQuantity(this.getAttribute('data-product-id'), this.value)">
                        </div>
                        <div class="item-subtotal" id="subtotal-${entry.key}">
                            <fmt:formatNumber value="${entry.value.subtotal}" pattern="#0.00"/>元
                        </div>
                        <!-- 修复：使用data属性传递productId，避免EL表达式解析问题 -->
                        <div class="delete-btn" data-product-id="${entry.key}" onclick="deleteItem(this.getAttribute('data-product-id'))">×</div>
                    </div>
                </c:forEach>
            </div>

            <!-- 总价计算 -->
            <div class="cart-summary">
                <div class="summary-title">
                    合计：<span class="total-price" id="totalPrice">
                        <c:set var="total" value="0" />
                        <c:forEach items="${sessionScope.cart}" var="item">
                            <c:set var="total" value="${total + item.value.subtotal}" />
                        </c:forEach>
                        <fmt:formatNumber value="${total}" pattern="#0.00"/>元
                    </span>
                </div>
                <!-- 修改：传递用户登录状态 -->
                <button class="checkout-btn" onclick="checkout(${not empty sessionScope.user})">去结算</button>
            </div>
        </c:if>
    </div>
</main>

<!-- 引入尾部 -->
<jsp:include page="footer.jsp" />

<!-- 支付模态框 -->
<div id="paymentModal" class="payment-modal">
    <div class="payment-content">
        <div class="payment-header">
            <h3>确认支付</h3>
            <span class="close-btn" onclick="closePaymentModal()">&times;</span>
        </div>
        <div id="paymentProductInfo" class="payment-product-info">
            <!-- 产品信息将在这里动态填充 -->
        </div>
        <div class="payment-total">
            <div style="display: flex; justify-content: space-between; font-weight: bold;">
                <span>总计:</span>
                <span id="paymentTotal" style="color: #e63946;">0.00元</span>
            </div>
        </div>
        <div class="payment-form">
            <h4>选择支付方式</h4>
            <div class="payment-method selected" onclick="selectPaymentMethod(this)">
                <input type="radio" name="paymentMethod" value="wechat" checked>
                <span>微信支付</span>
            </div>
            <div class="payment-method" onclick="selectPaymentMethod(this)">
                <input type="radio" name="paymentMethod" value="alipay">
                <span>支付宝</span>
            </div>
            <div class="payment-method" onclick="selectPaymentMethod(this)">
                <input type="radio" name="paymentMethod" value="card">
                <span>银行卡</span>
            </div>
            <button class="payment-button" onclick="processPayment()">立即支付</button>
        </div>
    </div>
</div>

<!-- 成功提示 -->
<div id="successMessage" class="success-message">
    <p>支付成功!</p>
</div>

<!-- 购物车操作JS -->
<script>
    const contextPath = "${pageContext.request.contextPath}";
    let selectedPaymentMethod = "wechat";

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        console.log('购物车页面已加载');
    });

    function updateQuantity(productId, quantity) {
        // 添加参数验证
        if (!productId || productId === '' || productId === 'null') {
            console.error('Invalid productId:', productId);
            alert('参数错误：商品ID无效');
            return;
        }

        console.log('Updating quantity for productId:', productId, 'quantity:', quantity);

        // 构建URL，确保正确的路径
        let url;
        if (contextPath && contextPath !== "") {
            url = `${contextPath}/cart/update`;
        } else {
            url = `/cart/update`;
        }

        // 使用FormData来确保参数正确传递
        const formData = new FormData();
        formData.append('productId', productId);
        formData.append('quantity', quantity);

        console.log("Update URL:", url);
        console.log("Form data:", 'productId=' + productId + '&quantity=' + quantity);

        fetch(url, {
            method: 'POST',
            body: formData
        })
            .then(response => {
                // 首先检查响应状态
                if (!response.ok) {
                    throw new Error('网络响应异常: ' + response.status);
                }
                // 尝试解析为JSON
                return response.json().catch(() => {
                    // 如果解析失败，返回原始文本
                    return response.text().then(text => {
                        throw new Error('服务器返回了非JSON数据: ' + text.substring(0, 100));
                    });
                });
            })
            .then(data => {
                if (data.success) {
                    // 从DOM元素获取价格信息
                    const cartItem = document.querySelector(`[data-id="${productId}"]`);
                    const priceStr = cartItem.getAttribute('data-price');
                    const price = parseFloat(priceStr);

                    // 更新小计显示
                    const subtotalElement = document.getElementById(`subtotal-${productId}`);
                    if (subtotalElement) {
                        const newSubtotal = (price * quantity).toFixed(2);
                        subtotalElement.textContent = newSubtotal + '元';
                    }

                    // 重新计算并更新总价
                    updateTotalPrice();

                    // 更新购物车数量
                    updateCartCount(data.cartCount);
                } else {
                    alert('更新数量失败: ' + data.message);
                    // 恢复原始值
                    const input = document.querySelector(`[data-id="${productId}"] .quantity-input`);
                    if (input) input.value = input.defaultValue;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败: ' + error.message);
                // 恢复原始值
                const input = document.querySelector(`[data-id="${productId}"] .quantity-input`);
                if (input) input.value = input.defaultValue;
            });
    }

    function deleteItem(productId) {
        // 添加参数验证
        if (!productId || productId === '' || productId === 'null') {
            console.error('Invalid productId:', productId);
            alert('参数错误：商品ID无效');
            return;
        }

        console.log('Deleting item with productId:', productId);

        if (confirm('确定要删除此商品吗？')) {
            // 构建URL，确保正确的路径
            let url;
            if (contextPath && contextPath !== "") {
                url = `${contextPath}/cart/delete`;
            } else {
                url = `/cart/delete`;
            }

            // 使用FormData来确保参数正确传递
            const formData = new FormData();
            formData.append('productId', productId);

            console.log("Delete URL:", url);
            console.log("Form data:", 'productId=' + productId);

            fetch(url, {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    // 首先检查响应状态
                    if (!response.ok) {
                        throw new Error('网络响应异常: ' + response.status);
                    }
                    // 尝试解析为JSON
                    return response.json().catch(() => {
                        // 如果解析失败，返回原始文本
                        return response.text().then(text => {
                            throw new Error('服务器返回了非JSON数据: ' + text.substring(0, 100));
                        });
                    });
                })
                .then(data => {
                    if (data.success) {
                        const item = document.querySelector(`[data-id="${productId}"]`);
                        if (item) item.remove();

                        // 重新计算并更新总价
                        updateTotalPrice();

                        // 更新购物车数量
                        updateCartCount(data.cartCount);
                        if (data.cartCount == 0 || data.cartCount === '0') {
                            window.location.reload();
                        }
                    } else {
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
    }

    // 统一的总价更新函数
    function updateTotalPrice() {
        let newTotal = 0;
        document.querySelectorAll('.cart-item').forEach(item => {
            const priceStr = item.getAttribute('data-price');
            const price = parseFloat(priceStr);
            const quantity = parseInt(item.querySelector('.quantity-input').value);
            if (!isNaN(price) && !isNaN(quantity)) {
                newTotal += price * quantity;
            }
        });

        const totalElement = document.getElementById('totalPrice');
        if (totalElement) {
            totalElement.textContent = newTotal.toFixed(2) + '元';
        }
    }

    // 实现结算功能，弹出支付模态框
    function checkout(isLoggedIn) {
        if (!isLoggedIn) {
            alert('请先登录！');
            window.location.href = contextPath + '/login.jsp';
        } else {
            // 检查购物车是否为空
            const cartItems = document.querySelectorAll('.cart-item');
            if (cartItems.length === 0) {
                alert('购物车为空，无法结算');
                return;
            }

            // 填充支付模态框
            populatePaymentModal();

            // 显示支付模态框
            document.getElementById('paymentModal').style.display = 'block';
        }
    }

    // 填充支付模态框中的产品信息
    function populatePaymentModal() {
        const paymentProductInfo = document.getElementById('paymentProductInfo');
        const paymentTotal = document.getElementById('paymentTotal');
        let total = 0;

        // 清空现有内容
        paymentProductInfo.innerHTML = '';

        // 填充产品信息
        document.querySelectorAll('.cart-item').forEach(item => {
            const productId = item.getAttribute('data-id');
            const productName = item.querySelector('.cart-item-name').textContent;
            const productPrice = parseFloat(item.getAttribute('data-price'));
            const quantity = parseInt(item.querySelector('.quantity-input').value);
            const subtotal = productPrice * quantity;
            total += subtotal;

            // 创建产品项HTML
            const productItem = document.createElement('div');
            productItem.className = 'product-item';
            productItem.innerHTML = `
                <div class="product-image">
                    ${item.querySelector('.cart-item-image img').outerHTML}
                </div>
                <div class="product-details">
                    <div class="product-name">${productName}</div>
                    <div class="product-quantity">数量: ${quantity}</div>
                </div>
                <div class="product-price">${subtotal.toFixed(2)}元</div>
            `;

            paymentProductInfo.appendChild(productItem);
        });

        // 更新总价
        paymentTotal.textContent = total.toFixed(2) + '元';
    }

    // 选择支付方式
    function selectPaymentMethod(methodElement) {
        // 移除所有选中状态
        document.querySelectorAll('.payment-method').forEach(method => {
            method.classList.remove('selected');
        });
        // 添加选中状态
        methodElement.classList.add('selected');
        // 获取选中的支付方式
        selectedPaymentMethod = methodElement.querySelector('input').value;
    }

    // 处理支付
    function processPayment() {
        // 显示成功提示
        const successMessage = document.getElementById('successMessage');
        successMessage.style.display = 'block';

        // 隐藏支付模态框
        closePaymentModal();

        // 3秒后跳转到订单页

    // 关闭支付模态框
    function closePaymentModal() {
        document.getElementById('paymentModal').style.display = 'none';
    }

    function updateCartCount(count) {
        const cartCountElement = document.querySelector('.cart-count');
        if (cartCountElement) {
            cartCountElement.textContent = count;
            cartCountElement.style.display = count > 0 ? 'inline' : 'none';
        }
    }

    // 页面加载时验证购物车项目
    document.addEventListener('DOMContentLoaded', function() {
        console.log('Page loaded, validating cart items...');
        document.querySelectorAll('.cart-item').forEach(item => {
            const productId = item.getAttribute('data-id');
            console.log('Cart item productId:', productId);
            if (!productId || productId === '' || productId === 'null') {
                console.error('Found invalid productId in cart item:', item);
            }
        });
    });}
</script>
</body>
</html>